package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminUserLoginMapper;
import com.heima.admin.service.AdminUserLoginService;
import com.heima.model.admin.dtos.AdminLoginDto;
import com.heima.model.admin.pojos.AdminUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminUserLoginServiceImpl extends ServiceImpl<AdminUserLoginMapper, AdminUser> implements AdminUserLoginService {

    /**
     * 用户登录
     *
     * @param adminLoginDto
     * @return
     */
    @Override
    public ResponseResult login(AdminLoginDto adminLoginDto) {
        if (adminLoginDto == null || StringUtils.isEmpty(adminLoginDto.getName()) || StringUtils.isEmpty(adminLoginDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        AdminUser adminUser = getOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getName, adminLoginDto.getName()));
        if (adminUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String password = DigestUtils.md5DigestAsHex((adminLoginDto.getPassword() + adminUser.getSalt()).getBytes());
        if (!password.equals(adminUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Map map = new HashMap();
        adminUser.setPassword(null);
        adminUser.setSalt(null);
        map.put("user", adminUser);
        String token = AppJwtUtil.getToken(adminUser.getId().longValue());
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
